package com.edu.neusoft.phone_sale.dto;

import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.util.regex.Pattern;

@Data
public class UserDto {

    @ApiModelProperty(value = "用户名", required = true)
    private String username;

    @ApiModelProperty(value = "密码", required = true)
    private String password;

    public void validate() {
        try {
            validateUsername(username);
            validatePassword(password);
        } catch (IllegalArgumentException e) {
            throw new UserValidationException(e.getMessage());
        }
    }

    private void validateUsername(String username) {
        if (username == null || username.isEmpty()) {
            throw new IllegalArgumentException("用户名不能为空");
        }
        if (username.length() < 6 || username.length() > 20) {
            throw new IllegalArgumentException("用户名长度必须在 6 到 20 个字符之间");
        }
        if (!Pattern.matches("^[a-zA-Z0-9_]+$", username)) {
            throw new IllegalArgumentException("用户名只能包含字母、数字和下划线");
        }
    }

    private void validatePassword(String password) {
        if (password == null || password.isEmpty()) {
            throw new IllegalArgumentException("密码不能为空");
        }
        if (password.length() < 8 || password.length() > 20) {
            throw new IllegalArgumentException("密码长度必须在 8 到 20 个字符之间");
        }
        if (!Pattern.matches("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]+$", password)) {
            throw new IllegalArgumentException("密码必须包含大写字母、小写字母、数字和特殊字符");
        }
    }
}

class UserValidationException extends RuntimeException {
    public UserValidationException(String message) {
        super(message);
    }
}